package com.sxfq.loansupermarket.backsystem.modular.weixin.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.GunsApplication;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.MembersUser;
import com.sxfq.loansupermarket.backsystem.modular.IntegralMall.entity.PointRewordInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.ReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchReturnVisitInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.IReturnVisitService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.IGetListService;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.SearchReservationsInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.service.IReservationsService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.*;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.service.IConsultantService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信开发者接入
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/marketPatientsCentral")
public class MarketPatientsCentralController extends BaseController {
    private String PREFIX = "/weixin/app/";

    protected final static Logger logger = LoggerFactory.getLogger(GunsApplication.class);
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SqlMapper sqlMapper;
    @Autowired
    IReservationsService reservationsService;

    @Autowired
    IGetListService getListService;
    @Autowired
    IReturnVisitService marketReturnVisitService;


    /**
     * 跳转患者列表
     */
    @RequestMapping("/patient_query/{obj}")
    public String patient_query(@PathVariable String obj,Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + obj+"/patient/patient_query.html";
    }

    /**
     * 市场患者列表加载
     */
    @RequestMapping(value = "/getMarketPatient", method = RequestMethod.POST)
    @ResponseBody
    public List<ReservationsInfo> getScoreShopping(String startFilingTime,String endFilingTime,String reach) {
        SearchReservationsInfo info=new SearchReservationsInfo();
        Page<ReservationsInfo> page = new Page<>();
        info.setStartIndex(0);
        info.setLimitIndex(50);
        info.setStartFilingTime(startFilingTime);
        info.setEndFilingTime(endFilingTime);
        info.setReach(reach);
        page.setCurrent(0);
        page.setSize(50);
        List<ReservationsInfo> list = reservationsService.selectPageListByStatusMap(page, info);
        return list;
    }

    /**
     * APP - 市场
     * 点击患者跳转页面 - 详情
     */
    @RequestMapping("/getMarketPatient_details/{reservationsId}")
    public String getMarketPatient_details(@PathVariable String reservationsId,Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql="select (CASE a.customer_sex " +
                " WHEN 1 THEN " +
                "  '男' " +
                "  WHEN 2 THEN " +
                "  '女' " +
                "  ELSE " +
                "  '未知' " +
                "  END " +
                "  ) as sex ," +
                "( " +
                " CASE a.customer_sex " +
                " WHEN 1 THEN " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait01.png' " +
                " WHEN 2 THEN " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait02.png' " +
                " ELSE " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait03.png' " +
                " END " +
                ") as avatar ,"+
                "a.* from reservations_info a where id ='"+reservationsId+"'";
        ReservationsInfo info=sqlMapper.selectOne(sql,ReservationsInfo.class);
        model.addAttribute("info",info);
        return PREFIX + "market/patient/patient_details.html";
    }


    /**
     * APP - 市场
     * 点击新建跳转页面 - 新建
     */
    @RequestMapping("/marketPatient_addTo")
    public String patient_addTo(Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        if (ShiroKit.getUser().getDepartmentList() == null) {
            String getListSql = "select a.department as department from " + redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"pay_service_grade_info",0) + " a where a.is_upper=1 group by a.department order by a.id;";
            List<DepartmentInfo> departmentList=sqlMapper.selectList(getListSql,DepartmentInfo.class);
            ShiroKit.getUser().setDepartmentList(departmentList);
        }
        if (ShiroKit.getSessionAttr("outpatientManagementList") == null) {
            List<Map<String, Object>> outpatientManagementList = getListService.outpatientManagementList();
            ShiroKit.setSessionAttr("outpatientManagementList", outpatientManagementList);
        }
        model.addAttribute("outpatientManagementList", ShiroKit.getSessionAttr("outpatientManagementList"));
        model.addAttribute("departmentList",ShiroKit.getUser().getDepartmentList());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        return PREFIX + "market/patient/patient_addTo.html";
    }

    /**
     * APP - 市场
     * 点击回访跳转页面 - 回访详情
     */
    @RequestMapping("/marketPatient_returnVisit/{id}")
    public String patient_returnVisit(@PathVariable String id,Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql="select * from reservations_info a where id ='"+id+"'";
        ReservationsInfo info=sqlMapper.selectOne(sql,ReservationsInfo.class);
        model.addAttribute("huifang",info.getHuifang());
        model.addAttribute("id",id);
        return PREFIX + "market/patient/patient_returnVisit.html";
    }

    //加载市场回访列表
    @RequestMapping(value = "/market_returnVisit_list", method = RequestMethod.POST)
    @ResponseBody
    public List<ReturnVisitInfo> market_returnVisit_list(String startTime, String endTime,String area, String outpatientName,String department, String accessDisease,
                                                         String appointmentPayService, String statuss,String status, String oneChannel,String twoChannel,
                                                         String thrChannel,String archiving,String follower,HttpServletRequest request) {
        SearchReturnVisitInfo info=new SearchReturnVisitInfo();
        Page<ReturnVisitInfo> page =  new Page<>();
        info.setStartTime(startTime);
        info.setEndTime(endTime);
        info.setArea(area);
        info.setOutpatientName(outpatientName);
        info.setDepartment(department);
        info.setAccessDisease(accessDisease);
        info.setAppointmentPayService(appointmentPayService);
        info.setStatuss(statuss);
        info.setStatus(status);
        info.setOneChannel(oneChannel);
        info.setTwoChannel(twoChannel);
        info.setThrChannel(thrChannel);
        info.setArchiving(archiving);
        info.setFollower(follower);
        page.setCurrent(0);
        page.setSize(500);
        List<ReturnVisitInfo> list = marketReturnVisitService.selectPageListByQuery(page, info);
        return list;
    }

    //跳转到添加回访页面--市场
    @RequestMapping("/market_patient_addVisit/{id}")
    public String market_patient_addVisit(@PathVariable String id ,Model model) {
        String tableHead = redisTemplate.opsForList().index(ShiroKit.getUser().getAccount()+"Abbreviation",0)+"";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }

        String sql="select (CASE a.customer_sex " +
                " WHEN 1 THEN " +
                "  '男' " +
                "  WHEN 2 THEN " +
                "  '女' " +
                "  ELSE " +
                "  '未知' " +
                "  END " +
                "  ) as sex ," +
                "( " +
                " CASE a.customer_sex " +
                " WHEN 1 THEN " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait01.png' " +
                " WHEN 2 THEN " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait02.png' " +
                " ELSE " +
                " 'https://pynnn.oss-cn-hangzhou.aliyuncs.com/weixin-img/app/portrait03.png' " +
                " END " +
                ") as avatar ,"+
                "a.* from reservations_info a where id ='"+id+"'";
        ReservationsInfo info=sqlMapper.selectOne(sql,ReservationsInfo.class);
        model.addAttribute("info",info);
        return PREFIX + "market/patient/patient_addVisit.html";
    }


    /**
     * 添加回访-市场
     */
    @RequestMapping(value = "/patient_addVisitOk", method = RequestMethod.POST)
    @ResponseBody
    public int patient_addVisitOk(String reservationsId,String revisitContent,String appointmentTime,String statuss,String followers){
        String sqlselecthf = "select id,huifang,belonger,archiving,follower,filing_time,customer_phone,customer_name " +
                "from reservations_infosc a where a.id='" +reservationsId+ "' limit 0,1";
        ReservationsInfo reservationsInfo = sqlMapper.selectOne(sqlselecthf, ReservationsInfo.class);
        String isEffectiveSql = ",lasthuifangtime='" + DateTimeKit.now() + "'";
        if (reservationsInfo != null) {
            if (reservationsInfo.getHuifang() == null || reservationsInfo.getHuifang() == "") {
                String updatesql = "update reservations_info a set a.follower='" + followers + "', a.statuss='" + statuss + "'," +
                        "a.huifang=CONCAT(concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + revisitContent + "')) " + isEffectiveSql + ",appointment_time=" + appointmentTime + "," +
                        "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where id='" + reservationsId + "'";
                String updatesqlsc = "update reservations_infosc a set a.follower='" + followers + "', a.statuss='" + statuss + "'," +
                        " a.huifang=CONCAT(concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" +
                        " " + revisitContent + "')) " + isEffectiveSql + ",appointment_time='" + appointmentTime + "'," +
                        "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where id='" + reservationsId + "'";
                sqlMapper.update(updatesql);
                sqlMapper.update(updatesqlsc);
            } else {
                String updatesql = "update reservations_info a set a.follower='" + followers + "', a.statuss='" + statuss + "'," +
                        " a.huifang=CONCAT(huifang,concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" +
                        " " + revisitContent + "')) " + isEffectiveSql + ",appointment_time='" + appointmentTime + "'," +
                        "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where id='" + reservationsId + "'";
                String updatesqlsc = "update reservations_infosc a set a.follower='" + followers + "', a.statuss='" + statuss + "'," +
                        " a.huifang=CONCAT(huifang,concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" +
                        " " + revisitContent + "')) " + isEffectiveSql + ",appointment_time='" + appointmentTime + "'," +
                        "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where id='" + reservationsId + "'";
                sqlMapper.update(updatesql);
                sqlMapper.update(updatesqlsc);
            }
        }else{
            String sqlselec2= "select id,huifang,belonger,archiving,follower,filing_time,customer_phone,customer_name " +
                    "from reservations_info a where a.id='" + reservationsId + "' limit 0,1";
            reservationsInfo = sqlMapper.selectOne(sqlselec2, ReservationsInfo.class);
            if (reservationsInfo.getHuifang() == null || reservationsInfo.getHuifang() == "") {
                String updatesql = "update reservations_info a set a.follower='" + followers + "', a.statuss='" + statuss + "'," +
                        "a.huifang=CONCAT(concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" + revisitContent + "')) " + isEffectiveSql + ",appointment_time='" + appointmentTime + "'," +
                        "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where id='" + reservationsId + "'";
                sqlMapper.update(updatesql);
            } else {
                String updatesql = "update reservations_info a set a.follower='" + followers + "', a.statuss='" + statuss + "'," +
                        " a.huifang=CONCAT(huifang,concat(char(10),' ,<b>" + DateTimeKit.now() + "</b>[" + ShiroKit.getUser().getAccount() + "]:" +
                        " " + revisitContent + "')) " + isEffectiveSql + ",appointment_time='" + appointmentTime + "'," +
                        "return_to_remark='" + ShiroKit.getUser().getAccount() + "' where id='" + reservationsId + "'";
                sqlMapper.update(updatesql);
            }
        }
        return 1;
    }


}